import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import { prisma, dbOperation } from '@/lib/db';

// 获取邀请详情
export async function GET(request: NextRequest) {
  console.log('=== 获取邀请详情 API 被调用 ===');
  
  try {
    // 获取查询参数
    const searchParams = request.nextUrl.searchParams;
    const token = searchParams.get('token');

    console.log('请求参数:', { token });

    if (!token) {
      console.log('缺少邀请令牌');
      return NextResponse.json(
        { success: false, message: '缺少邀请令牌' },
        { status: 400 }
      );
    }

    console.log('开始查找邀请记录...');
    
    // 查找对应的邀请记录
    const invite = await dbOperation(async () => {
      return prisma.projectInvite.findFirst({
        where: {
          token,
          expires: {
            gt: new Date(),
          },
          acceptedAt: null,
        },
        include: {
          project: {
            select: {
              id: true,
              name: true,
              description: true,
            },
          },
          inviter: {
            select: {
              id: true,
              name: true,
              image: true,
            },
          },
        },
      });
    });

    console.log('查找邀请结果:', invite);

    if (!invite.success) {
      console.error('查找邀请失败:', invite.error);
      return NextResponse.json(
        { success: false, message: '查找邀请失败', error: invite.error },
        { status: 500 }
      );
    }

    if (!invite.data) {
      console.log('邀请无效或已过期');
      return NextResponse.json(
        { success: false, message: '邀请无效或已过期' },
        { status: 404 }
      );
    }

    // 格式化角色文本
    const roleText =
      invite.data.role === 'ADMIN'
        ? '管理员'
        : invite.data.role === 'MEMBER'
        ? '成员'
        : '观察者';

    console.log('返回邀请详情');
    
    // 返回邀请详情
    return NextResponse.json({
      success: true,
      data: {
        email: invite.data.email,
        project: invite.data.project,
        role: invite.data.role,
        roleText,
        message: invite.data.message,
        expires: invite.data.expires,
        inviter: invite.data.inviter,
      },
    });
  } catch (error: any) {
    console.error('获取邀请详情失败:', error);
    return NextResponse.json(
      { success: false, message: '获取邀请详情失败', error: error.message },
      { status: 500 }
    );
  }
}

// 接受项目邀请
export async function POST(request: NextRequest) {
  console.log('=== 接受邀请 API 被调用 ===');
  
  try {
    // 检查用户是否已认证
    const session = await auth();
    console.log('用户会话:', session?.user?.email);

    if (!session?.user) {
      console.log('用户未认证');
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 解析请求体
    const body = await request.json();
    const { token } = body;

    console.log('接受邀请请求:', { token, userEmail: session.user.email });

    if (!token) {
      console.log('缺少邀请令牌');
      return NextResponse.json(
        { success: false, message: '缺少邀请令牌' },
        { status: 400 }
      );
    }

    // 查找对应的邀请记录
    console.log('开始查找邀请记录...');
    const invite = await dbOperation(async () => {
      return prisma.projectInvite.findFirst({
        where: {
          token,
          expires: {
            gt: new Date(),
          },
          acceptedAt: null,
        },
        include: {
          project: {
            select: {
              id: true,
              name: true,
            },
          },
        },
      });
    });

    console.log('查找邀请结果:', invite);

    if (!invite.success) {
      console.error('查找邀请失败:', invite.error);
      return NextResponse.json(
        { success: false, message: '查找邀请失败', error: invite.error },
        { status: 500 }
      );
    }

    if (!invite.data) {
      console.log('邀请无效或已过期');
      return NextResponse.json(
        { success: false, message: '邀请无效或已过期' },
        { status: 404 }
      );
    }

    console.log('邀请详情:', {
      inviteEmail: invite.data.email,
      userEmail: session.user.email,
      projectId: invite.data.projectId
    });

    // 验证邀请的邮箱是否与当前用户邮箱匹配
    if (invite.data.email !== session.user.email) {
      console.log('邮箱不匹配:', { inviteEmail: invite.data.email, userEmail: session.user.email });
      return NextResponse.json(
        { success: false, message: '邀请邮箱与当前登录账号不匹配' },
        { status: 403 }
      );
    }

    // 检查用户是否已经是项目成员
    console.log('检查用户是否已是项目成员...');
    const existingMember = await dbOperation(async () => {
      return prisma.projectUser.findFirst({
        where: {
          projectId: invite.data.projectId,
          userId: session.user.id,
        },
      });
    });

    if (!existingMember.success) {
      console.error('检查用户关系失败:', existingMember.error);
      return NextResponse.json(
        { success: false, message: '检查用户关系失败', error: existingMember.error },
        { status: 500 }
      );
    }

    if (existingMember.data) {
      console.log('用户已是项目成员');
      // 更新邀请状态为已接受
      await dbOperation(async () => {
        return prisma.projectInvite.update({
          where: { id: invite.data.id },
          data: { 
            acceptedAt: new Date(),
            acceptedById: session.user.id,
          },
        });
      });

      return NextResponse.json(
        { success: false, message: '您已经是该项目的成员', project: invite.data.project },
        { status: 400 }
      );
    }

    // 在事务中执行添加成员并更新邀请状态的操作
    console.log('开始执行事务...');
    const transaction = await dbOperation(async () => {
      return prisma.$transaction([
        // 添加用户为项目成员
        prisma.projectUser.create({
          data: {
            projectId: invite.data.projectId,
            userId: session.user.id,
            role: invite.data.role,
          },
        }),
        // 更新邀请状态为已接受
        prisma.projectInvite.update({
          where: { id: invite.data.id },
          data: { 
            acceptedAt: new Date(),
            acceptedById: session.user.id,
          },
        }),
        // 创建活动记录
        prisma.activity.create({
          data: {
            userId: session.user.id,
            type: 'PROJECT_JOINED',
            entityId: invite.data.projectId,
            data: {
              projectId: invite.data.projectId,
              projectName: invite.data.project.name,
              role: invite.data.role,
            },
          },
        }),
      ]);
    });

    if (!transaction.success) {
      console.error('事务执行失败:', transaction.error);
      return NextResponse.json(
        { success: false, message: '接受邀请失败', error: transaction.error },
        { status: 500 }
      );
    }

    console.log('事务执行成功');

    // 创建通知
    await dbOperation(async () => {
      return prisma.notification.create({
        data: {
          type: 'PROJECT_UPDATE',
          title: '成员加入',
          content: `${session.user.name || '新成员'} 已加入项目 ${invite.data.project.name}`,
          recipients: {
            create: {
              // 通知项目所有者和管理员
              userId: invite.data.inviterId,
            },
          },
        },
      });
    });

    console.log('邀请接受完成，返回成功响应');
    return NextResponse.json({
      success: true,
      message: '成功加入项目',
      data: {
        projectId: invite.data.projectId,
        projectName: invite.data.project.name,
        role: invite.data.role,
      },
    });
  } catch (error: any) {
    console.error('接受项目邀请失败:', error);
    return NextResponse.json(
      { success: false, message: '接受项目邀请失败', error: error.message },
      { status: 500 }
    );
  }
}


